import { Button, message, notification } from 'antd';
import { useIntl } from 'umi';
import defaultSettings from '../config/defaultSettings';
import loggerCreator from '@hz/logger';
import { init } from '@hz/beidou-js-sdk';
// import { config } from '@/utils/config.util';

const { pwa } = defaultSettings;
const isHttps = document.location.protocol === 'https:';
const logger = loggerCreator.createLogger('request');
logger.level = 'trace';
const isLogServer = typeof window === 'undefined';
function initLogger() {
  // 日志插件使用
  try {
    if (isLogServer) {
      loggerCreator.injectApm();
      logger.trace('this is a trace logger');
    } else {
      logger.trace('this is a trace logger');
    }
  } catch (err) {
    logger.error(err);
  }
}
function initBeiDou() {
  const beidouInstance = init({
    app_id: 'd1bed613223c4ba78ec3eb78dffad88c',
    app_version: '1.0.1',
    // show_log: false,
    // 下面的一般情况请不要开启，会记录所有的用户行为，上行流量会很大
    heatmap: {
      // 是否开启点击图，默认 default 表示开启，自动采集 $WebClick 事件，可以设置 'not_collect' 表示关闭
      clickmap: 'default',
      // 是否开启触达注意力图，默认 not_collect 表示关闭，不会自动采集 $WebStay 事件，可以设置 'default' 表示开启
      scroll_notice_map: 'default',
    },
  });
  const beidouExtraData = {};
  beidouInstance.registerPage({ ...beidouExtraData });
  beidouInstance.quick('autoTrack');
}

initLogger();
initBeiDou();
// if pwa is true
if (pwa) {
  // Notify user if offline now
  window.addEventListener('sw.offline', () => {
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
  });

  // Pop up a prompt on the page asking the user if they want to use the latest version
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
    const reloadSW = async () => {
      // Check if there is sw whose state is waiting in ServiceWorkerRegistration
      // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      // Send skip-waiting event to waiting SW with MessageChannel
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (msgEvent) => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });
      // Refresh current page to use the updated HTML and other assets after SW has skiped waiting
      window.location.reload(true);
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
      </Button>
    );
    notification.open({
      message: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
      btn,
      key,
      onClose: async () => null,
    });
  });
} else if ('serviceWorker' in navigator && isHttps) {
  // unregister service worker
  const { serviceWorker } = navigator;
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then((sws) => {
      sws.forEach((sw) => {
        sw.unregister();
      });
    });
  }
  serviceWorker.getRegistration().then((sw) => {
    if (sw) sw.unregister();
  });

  // remove all caches
  // @ts-ignore
  if (window.caches && window.caches.keys) {
    caches.keys().then((keys) => {
      keys.forEach((key) => {
        caches.delete(key);
      });
    });
  }
}
